/**
 * 对应jsp：pages/app/home/home.jsp
 * Created by 杨浩宇 on 2016-01-06.
 */
define(["require", "jquery", 'public/app','divContainer'], function (require, $, app,divContainer) {

    function Home($container) {
        this._$container = $container;
        this._initLayout();
        this._init();
        this._$container.find("#desktop").divContainer({"id":"home"});

    }

    Home.prototype = {
        _initLayout: function () {
            $('#indexFrame').layout();
        },
        /**
         * 初始化url地址
         * @private
         */
        _initUrlPath: function () {
            this.urlPaths = {
                activeMenus: app.urlBuild("/dirms/security/authority/findNavAuthoritesByUser")//查询导航菜单
            };
        },

        /**
         * 初始化类
         * @private
         */
        _init: function () {
            this._initUrlPath();

            var self = this;

            //通过DataReady先准备好所有页面需要的数据，然后再对页面控件进行统一的初始化
            var dataReady = app.getDataReady();
            dataReady.pushDataSource({//逐个放入所有数据源
                url: this.urlPaths.activeMenus,
                key: 'menu'
        });
            dataReady.once(function (readyData) {//所有数据源都加载后执行一次方法
                self._initComponents(readyData);
            });
        },

        /**
         * 初始化控件
         * @param readyData
         * @private
         */
        _initComponents: function (readyData) {
            this._initLogin();
            this._initNavMenu(readyData.menu.data);
            this._initTab();
            this._initUserInfo();
            this._initEventBinding();
        },

        /**
         * 初始化菜单
         * @param menus
         * @private
         */
        _initNavMenu: function (menus) {
            this._initMenuLevel(menus, 1);
            //ajax获取菜单
            $('#headMenu').headMenu({
                menus: menus
            });
            //$("#headMenu").after('<div id="menus_switch" class="menus_close"></div>');
            $("#headMenuObj").height($("#headMenu").height() - 22 - 65);
            var menuh = $('#headMenuObj').height();
            var requireH = $('#headMenuObj .menu_lv1_Obj').height();
            if (menuh > requireH) {
                $('#headMenuObj').width(43);
            } else {
                $('#headMenuObj').width(59);
            }
        },

        _initMenuLevel: function (menus, level) {
            var self = this;
            $.each(menus, function (index, item) {
                item.level = level;
                if (!app.utils.isNone(item.children) && item.children.length > 0) {
                    self._initMenuLevel(item.children, level + 1);
                }
            });
        },

        /**
         * 初始化home-tabs
         * @private
         */
        _initTab: function () {
            if ($("#home-tabs").length > 0) {
                $("#home-tabs").tabs({
                    plain: true,
                    narrow: false,
                    pill: false,
                    justified: false,
                    opens: new Array(),//维护一个数组对象，保存打开的tab页对应的title,index,页面对应的javascript模块对象
                    onBeforeClose: function (title, tabIndex) {//关闭tab页时，从opens属性中找到当前正在被关闭的tab信息，调用javascript模块对象的onBeforeDestroy完成模块对象的销毁
                        var tabOptions = $("#home-tabs").tabs("options");
                        $.each(tabOptions.opens, function (index, item) {//循环tabs维护的opens数组
                            //item包含index,title,module三个属性，分别指代tab的index、title、此tab对应的javascript模块对象
                            if (item.index === tabIndex) {
                                var module = item.module;
                                if ("onBeforeDestroy" in module) {
                                    module.onBeforeDestroy();//调用javascript模块对象的销毁方法。如果模块对象有需要销毁的代码，就应该写在该方法中
                                }
                            }
                        });
                    },
                    onClose: function (title, tabIndex) {//从tabs维护的opens数组中删除已经关闭的tab对象
                        var tabOptions = $("#home-tabs").tabs("options");
                        var indexArray = new Array();
                        $.each(tabOptions.opens, function (index, item) {
                            if (item.index === tabIndex) {
                                indexArray.push(index);
                            }
                        });
                        $.each(indexArray, function (index, item) {
                            tabOptions.opens.splice(item, 1);
                        });
                    }
                });
            }
        },
        //设置配置选项高度
        _setNavAutoHeight: function () {
            var self = this;
            var sHeight = $("body").height(), tmpH = parseInt(sHeight - 40 - 30), contentH = tmpH - 75, conMinH = 0;
            self._$container.find("#optionPanel .content .panel").each(function () {
                if ($(this).height() > conMinH) {
                    conMinH = $(this).height();
                }
            });
            if ((conMinH + 50) > contentH) { //最小高度大于可用高度时使用可用高度
                self._$container.find("#optionPanel").height(tmpH - 48);
                self._$container.find("#optionPanel .content").height(contentH - 40 - 30);
                self._$container.find("#optionPanel .content .tabs-panels").height(contentH - 40 - 30 - 22);
            } else {
                self._$container.find("#optionPanel").height(conMinH + 50 + 75 + 24);
                self._$container.find("#optionPanel .content").height(conMinH + 50);
                self._$container.find("#optionPanel .content .tabs-panels").height("auto");
            }
        },
        //初始化用户详情页面
        _initUserInfo: function () {
            var userName = app.getUserPrincipal().userName;
            $(".username").each(function () {
                $(this).html(userName);
            });
        },
        _initLogin: function () {
            $('#loginUser').text(app.getUserPrincipal()['userName']);
        },
        _launchFullscreen: function (element, $this) {
            if ($this.attr("class") === "full_screen") {
                if (element.requestFullscreen) {
                    element.requestFullscreen();
                } else if (element.mozRequestFullScreen) {
                    element.mozRequestFullScreen();
                } else if (element.webkitRequestFullscreen) {
                    element.webkitRequestFullscreen();
                } else if (element.msRequestFullscreen) {
                    element.msRequestFullscreen();
                }
                $this.attr("class", "close_full_screen");
            } else {
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                } else if (document.mozCancelFullScreen) {
                    document.mozCancelFullScreen();
                } else if (document.webkitExitFullscreen) {
                    document.webkitExitFullscreen();
                }
                $this.attr("class", "full_screen");
            }
        },

        /**
         * 事件绑定
         * @private
         */
        _initEventBinding: function () {
            var self = this;
            //为每个菜单绑定click事件
            $("#headMenu").find("a[data-id]").on("click", function () {
                var menuData = $(this).data();
                var opts = $.extend({}, menuData);
                opts.href = app.urlBuild(menuData.authurl);
                opts.executeClass = require(menuData.authpath);
                app.openHomeTab(opts);
            });
            //登出
            $(".sign_out").click(function () {
                $("#logoutForm").submit();
            });
            //打开、关闭全屏
            $("#screen_switch").on("click", function () {
                self._launchFullscreen(document.documentElement, $(this));
            });
            //查看用户详情
            $("#main_heaer .user").on("click", function () {
                self.actions.userInfo(self);
            });
            //打开、关闭菜单
            $("#menus_switch").on("click", function (e) {
                self.actions.menusOnOff(this);
            });
            $("#headMenuObj .menu_lv1_Obj").mouseover(function () {
                $("#headMenu").width(443);
            });
            //绑定关闭报表事件
            self._$container.find("#main_chart").on("click", ".close", function () {
                $(this).parent().parent().remove();
            });
            //配置项关闭开启
            self._$container.find("#optionPanel .head").on("click", function () {
                self.actions.navOptionClick(self);
            });
            //配置项 重置 按钮处理事件
            self._$container.find("#optionPanel .reset_but").on("click", function () {
                self.actions.resetNavOption(self);
            });
            //外部链接点击事件绑定
            self._$container.find(".external_links").on("click", function () {
                self.actions.externalLinksClick(self);
            })
            $(window).resize(function () {
                self.actions.windowResize(self);
            });
        },
        actions: {
            navOptionClick: function (self) {
                var $optionpanel = self._$container.find("#optionPanel");
                if ($optionpanel.css("right") === "10px") {
                    $optionpanel.animate({right: -233}, "fast");
                } else {
                    $optionpanel.animate({right: 10}, "fast");
                }
            },
            //用户详情查询
            userInfo: function (self) {
                var $adminInfo = $(".admin_info");
                $adminInfo.toggle();
                if ($adminInfo.is(":visible")) {
                    if (self._usr) {
                        clearTimeout(self._usr);
                    }
                    var usr = setTimeout(function () {
                        $adminInfo.slideUp("slow");
                    }, 10000);
                    self._usr = usr;
                }
            },
            //菜单打开关闭处理
            menusOnOff: function (self) {
                if ($(self).attr("class") === "menus_close") {
                    $("#main_left_menus").animate({width: 0}, "fast");
                    $("#headMenu").animate({width: 0}, "fast");
                    $("#home-tabs").parent().parent().animate({left: 0}, "fast");
                    $('#main_content').panel('resize', {
                        width: $("body").width()
                    });
                    $(self).attr("class", "menus_open");
                } else {
                    $('#main_content').panel('resize', {
                        width: $("body").width() - 43
                    });
                    $("#headMenu").width(43);
                    $(self).attr("class", "menus_close");
                }
            },
            //快捷菜单配置重置处理
            resetNavOption: function (self) {
                var savebean = [];
                self._$container.find('#option_tabs input:checkbox[name=chart_option]:checked').each(function () {
                    if ($(this).val()) {
                        savebean.push($(this).val());
                    }
                    ''
                });
                if (savebean.length > 0) {
                    $.ajax({
                        url: self.urlPaths.saveData,
                        contentType: 'application/json',
                        data: JSON.stringify(savebean),
                        type: 'POST',
                        success: function (e) {
                            self._$container.find("#optionPanel").animate({right: -233}, "fast");
                            if (Object.getOwnPropertyNames(self._navMapping).length > 0) {
                                self._initEchart(self._navMapping);
                            }
                        }
                    });
                }
            },
            windowResize: function (self) {
                $("#headMenu").width(43);
                $("#headMenuObj").height($("#headMenu").height() - 22 - 65);
                $("#menus_switch").attr("class", "menus_close");
                var menuh = $('#headMenuObj').height();
                var requireH = $('#headMenuObj .menu_lv1_Obj').height();
                if (menuh > requireH) {
                    $('#headMenuObj').width(43);
                } else {
                    $('#headMenuObj').width(59);
                }
            },
            //跳转页面
            addLinkClick: function (self) {
                $("#main_chart a").on("click", function () {
                    var navMapping = self._navDataMapping, id = $(this).attr("id");
                    if (navMapping[id]) {
                        var bean = navMapping[id];
                        var $tab = $("#home-tabs").tabs('getTab', bean.name);
                        if ($tab) {
                            $("#home-tabs").tabs('select', bean.name);
                        } else {
                            $("#home-tabs").tabs("add", {
                                title: bean.name,
                                closable: true,
                                id: Math.random(),
                                href: "/distnetwork/" + bean.authUrl,
                                onLoad: function () {
                                    var Bean = require(bean.authPath);
                                    var model = new Bean($(this));
                                }
                            });
                        }
                    }
                });
            },
            //外部链接点击处理事件
            externalLinksClick: function (self) {

            }
        }
    };

    return Home;
});